package com.crazymaker.springcloud.cloud.center.zuul.filter;


import com.crazymaker.springcloud.common.distribute.rateLimit.RateLimitService;
import com.crazymaker.springcloud.seckill.api.constant.SeckillConstants;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.recipes.atomic.DistributedAtomicInteger;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * zookeeper 秒杀限流
 */
@Slf4j
@Component
public class ZkRateLimitFilter extends ZuulFilter
{

    @Resource(name = "zkRateLimitServiceImpl" )
    RateLimitService rateLimitService;

    @Override
    public String filterType()
    {
//		pre：路由之前
//		routing：路由之时
//		post： 路由之后
//		error：发送错误调用
        return "pre";
    }

    /**
     * 过滤的顺序
     */
    @Override
    public int filterOrder()
    {
        return 0;
    }

    /**
     * 这里可以写逻辑判断，是否要过滤，true为永远过滤。
     */
    @Override
    public boolean shouldFilter()
    {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();

        if (request.getRequestURI().startsWith("/seckill-provider/api/seckill/do/v1" ))
        {
            return true;
        }

        return false;
    }

    /**
     * 过滤器的具体逻辑
     */
    @Override
    public Object run()
    {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();

        String goodId = request.getParameter("goodId" );
        if (goodId != null)
        {

            DistributedAtomicInteger counter = rateLimitService.getZookeeperCounter(goodId);
            try
            {

                log.info("参与抢购的人数：" + counter.get().preValue());
                if (counter.get().preValue() > SeckillConstants.MAX_ENTER)
                {
                    String msg = "参与抢购的人太多，请稍后再试一试";
                    errorhandle(ctx, msg);
                    return null;
                }
            } catch (Exception e)
            {
                e.printStackTrace();

                String msg = "计数异常,监控到商品是" + goodId;
                errorhandle(ctx, msg);
                return null;
            }

            return null;
        } else
        {

            String msg = "必须输入抢购的商品";
            errorhandle(ctx, msg);
            return null;
        }

    }


    /**
     * 统一的异常拦截
     */

    private void errorhandle(RequestContext ctx, String msg)
    {
        ctx.setSendZuulResponse(false);
        try
        {
            ctx.getResponse().setContentType("text/html;charset=utf-8" );
            ctx.getResponse().getWriter().write(msg);
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }


}